package com.woniuxy.rabbit.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.woniuxy.rabbit.feign.LightFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;



/**
 * @author ：yolo
 * @date ：Created in 2025/7/4 11:46
 * @description：
 * @modified By：
 * @version: $
 */
@Service
@Slf4j
public class RabbitService {



    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private LightFeign lightFeign;

    /**
     * 下单
     * @return
     */




    private void sendMessage(String exchange, String routingKey,String message) {
        CorrelationData correlationData = new CorrelationData();
        Message returnedMessage = new Message(JSON.toJSONBytes(message));
        correlationData.setReturnedMessage(returnedMessage);
        correlationData.getReturnedMessage().getMessageProperties().setReceivedExchange(exchange);
        correlationData.getReturnedMessage().getMessageProperties().setReceivedRoutingKey(routingKey);

        //幂等性 redis+token
        String token = IdUtil.fastUUID();
        redisTemplate.opsForValue().set(token,token,5, TimeUnit.MINUTES);
        //发送消息
        MessagePostProcessor messagePostProcessor = message1 -> {
            message1.getMessageProperties().setMessageId(token);
            return message1;
        };


        rabbitTemplate.convertAndSend(exchange, routingKey,message,messagePostProcessor,correlationData);
    }

    /**
     * 开关灯（used=1开灯，used=0关灯）
     * id: 灯的唯一标识
     * used: 1=开灯，0=关灯
     */
    public boolean updateUsedStatus(Long id, Integer used) {
        try {
            // 开灯时，发送延迟关灯消息
            if (used != null && used == 1) {
                // 发送到延迟队列，15秒后自动关灯
                sendMessage("light.exchange", "light.autooff", String.valueOf(id));
            }

        }catch (Exception e){
            log.error(""+e);

        }
        // 通过feign远程调用infrastructure服务的开关灯接口
        return lightFeign.updateUsedStatus(id, used);
    }

    /**
     * 监听自动关灯队列，收到消息后自动关灯（手动应答）
     */
    @RabbitListener(queues = "light.off.queue")
    public void autoOffLight(String id, Channel channel, Message message) {
        try {
            // 自动关灯，调用 updateUsedStatus(id, 0)
            updateUsedStatus(Long.valueOf(id), 0);
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 处理异常，消息重新入队或丢弃
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
    }
}
